//
//  WNRankDetailVC.swift
//  WalkNovel
//
//  Created by Kevin on 2021/11/4.
//

import UIKit
import JXSegmentedView

class WNRankDetailVC: WNBaseVC {
    
    lazy var rankTabView: WNTableView = {
        let tab = WNTableView(frame: .zero, style: .plain)
        tab.register(RankBookCell.self, forCellReuseIdentifier: RankBookCell.identifier)
        tab.register(RankUserCell.self, forCellReuseIdentifier: RankUserCell.identifier)
        tab.delegate = self
        tab.dataSource = self
        tab.ly_emptyView = WNEmptyView.wn_loadStyle(descStr: .rank, imageStr: .common, tapBlock: { [weak self] in
            self?.rankListRequest()
        })
        tab.isHidden = true
        return tab
    }()
        
    var type = "BOOK"
    
    var bookArr = [BookDetailModel]()
    
    var userArr = [BookDetailModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewConfig() {
        wn_hidNavView()
        view.addSubview(rankTabView)
        rankTabView.snp.makeConstraints { make in
            make.top.left.right.equalTo(0)
            make.bottom.equalTo(-TabBarTotalHeight)
        }
    }
    
    override func dataConfig() {
        pageName = type == "BOOK" ? "書籍排行" : "用戶排行"
        listSettingRefresh()
        rankListRequest()
    }
    
    override func handleNoti() {
        NotificationCenter.default.addObserver(forName: WNNotiName.loginNoti, object: nil, queue: nil) { [weak self] not in
            self?.rankListRequest()
        }
    }
}

extension WNRankDetailVC {
    
    func listSettingRefresh() {
        rankTabView.mj_header = wn_refreshHeader(completion: { [weak self] in
            self?.page = 1
            self?.hasPage = false
            self?.rankListRequest()
        })
        
        rankTabView.mj_footer = wn_refreshFooter(completion: { [weak self] in
            if self?.page == 1 && self?.bookArr.count == 0 {
                self?.rankTabView.mj_footer?.endRefreshing()
                return
            }
            if !(self?.hasPage ?? false) {
                self?.rankTabView.mj_footer?.endRefreshingWithNoMoreData()
            }else {
                self?.page += 1
                self?.rankListRequest()
            }
        })
    }
    
    func rankListRequest() {
        provider_Rank.rx.request(.rankList(type, page))
            .asObservable().mapModel(BaseModel<[BookDetailModel]>.self)
            .subscribe(onNext: { [weak self] (model) in
                self?.rankTabView.isHidden = false
                self?.rankTabView.ly_emptyView.imageStr = EmptyImage.common.rawValue
                self?.rankTabView.ly_emptyView.detailStr = EmptyDesc.rank.rawValue
                self?.rankTabView.ly_emptyView.btnTitleStr = ""
                guard model.code == 0 else {
                    if (self?.isFirst ?? true) {
                        self?.rankTabView.ly_emptyView.imageStr = EmptyImage.serverBad.rawValue
                        self?.rankTabView.ly_emptyView.detailStr = EmptyDesc.serverBad.rawValue
                        self?.rankTabView.ly_emptyView.btnTitleStr = "點擊刷新"
                    }else {
                        self?.wn_toast(model.msg ?? "")
                    }
                    self?.rankTabView.mj_header?.endRefreshing()
                    self?.rankTabView.mj_footer?.endRefreshing()
                    self?.isFirst = false
                    return
                }
                if self?.page == 1 {
                    self?.bookArr.removeAll()
                    self?.rankTabView.mj_footer?.resetNoMoreData()
                }
                if let arr = model.data {
                    self?.hasPage = arr.count > 9
                    self?.bookArr += arr
                }else {
                    self?.rankTabView.mj_footer?.endRefreshingWithNoMoreData()
                }
                self?.rankTabView.reloadData()
                self?.rankTabView.mj_header?.endRefreshing()
                self?.rankTabView.mj_footer?.endRefreshing()
                self?.isFirst = false
            }, onError: { [weak self] (error) in
                self?.wn_toast("檢查網路連線")
                self?.rankTabView.ly_emptyView.imageStr = EmptyImage.netWork.rawValue
                self?.rankTabView.ly_emptyView.detailStr = EmptyDesc.netWork.rawValue
                self?.rankTabView.ly_emptyView.btnTitleStr = "點擊刷新"
                self?.rankTabView.mj_header?.endRefreshing()
                self?.rankTabView.mj_footer?.endRefreshing()
                self?.rankTabView.isHidden = false
            }).disposed(by: rx.disposeBag)
    }
}

extension WNRankDetailVC: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return bookArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if type == "BOOK" {
            let cell = tableView.dequeueReusableCell(withIdentifier: RankBookCell.identifier, for: indexPath) as! RankBookCell
            cell.model = bookArr[indexPath.item]
            cell.numImage.image = UIImage(named: indexPath.item < 3 ? "book_\(indexPath.item)" : "")
            cell.numLabel.text = "\(indexPath.item+1)"
            cell.numLabel.isHidden = indexPath.item < 3
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: RankUserCell.identifier, for: indexPath) as! RankUserCell
            cell.model = bookArr[indexPath.item]
            cell.numImage.image = UIImage(named: indexPath.item < 3 ? "user_\(indexPath.item)" : "")
            cell.numLabel.text = "\(indexPath.item+1)"
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if type == "BOOK" {
            wn_pushBookVC(bookArr[indexPath.item].bookId ?? "")
        }else {
            
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return type == "BOOK" ? (scaleWidth(90)+12) : (scaleWidth(58)+12)
    }
}

extension WNRankDetailVC: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
